﻿package com.badibadi.activity;

import java.io.ObjectOutputStream.PutField;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import com.badibadi.abcpinying.CharacterParser;
import com.badibadi.abcpinying.ClearEditText;
import com.badibadi.abcpinying.PinyinComparator;
import com.badibadi.abcpinying.SideBar;
import com.badibadi.abcpinying.SideBar.OnTouchingLetterChangedListener;
import com.badibadi.abcpinying.ChoiceCrewAdapter;
import com.badibadi.abcpinying.SortModel;
import com.badibadi.infos.Results;
import com.badibadi.mytools.Constants;
import com.badibadi.mytools.JSONUtils;
import com.badibadi.mytools.MyThreadTool;
import com.badibadi.mytools.Utils;
import com.badibadi.uniclubber.R;
import com.libjph.util.StringUtil;
import com.view.my_view.MyCheckBox;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.Button;
import android.widget.ExpandableListView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

/**
 * 选择需要被邀请的好友(站内邀请好友列表)
 * 
 * @author Administrator Toast.make
 */
public class ChoiceCrewActivity extends BaseActivity {

	private ListView sortListView;
	private SideBar sideBar;
	private TextView dialog;
	private ChoiceCrewAdapter adapter;
	private ClearEditText mClearEditText;
	private Button Finish_btn;
	private Message message;
	private Bundle bundle;

	/**
	 * 汉字转换成拼音的类
	 */
	private CharacterParser characterParser;
	private List<SortModel> SourceDateList;

	/**
	 * 根据拼音来排列ListView里面的数据类
	 */
	private PinyinComparator pinyinComparator;

	/**
	 * 选择所有的checkbox
	 */
	private CheckBox checkall;
	/**
	 * 为了让CheckBox不让他响应一次侦听事件而弄的
	 */
	private boolean isSelectClick = false;

	private List<SortModel> List;
	private String pageNum = "9999";
	private String fid = "-1";

	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				Utils.ExitPrgress(ChoiceCrewActivity.this);
				try {
					Utils.showMessage(ChoiceCrewActivity.this, getResources()
							.getString(R.string.l_net_error));
				} catch (Exception e) {
					// TODO: handle exception
				}
				break;
			case 2:
				Utils.ExitPrgress(ChoiceCrewActivity.this);

				// initViews();
				Updata();

				break;
			case 3:
				Utils.ExitPrgress(ChoiceCrewActivity.this);
				// onLoad();
				try {
					Utils.showMessage(ChoiceCrewActivity.this, getResources()
							.getString(R.string.l_xa10));
				} catch (Exception e) {
					// TODO: handle exception
				}
				break;
			case 4:
				Utils.ExitPrgress(ChoiceCrewActivity.this);
				try {
					// Utils.showMessage(PinyinSeeOtherPeopleFriendActivity.this,
					// results2.getRetmsg());
					Intent intent = new Intent();
					intent.putExtra("res", msg.getData().getString("res"));
					setResult(21, intent);
					finish();
				} catch (Exception e) {
					// TODO: handle exception
				}
			default:
				break;
			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		goToTheTitle();
		setContentView(R.layout.choice_crew);
		initViews();
		initInterNet();

	}

	private void initViews() {

		// 实例化汉字转拼音类
		characterParser = CharacterParser.getInstance();
		pinyinComparator = new PinyinComparator();
		sideBar = (SideBar) findViewById(R.id.sidrbar);
		dialog = (TextView) findViewById(R.id.dialog);
		Finish_btn = (Button) findViewById(R.id.Finish_btn);
		SourceDateList = new ArrayList<SortModel>();
		sideBar.setTextView(dialog);

		// 设置右侧触摸监听
		sideBar.setOnTouchingLetterChangedListener(new OnTouchingLetterChangedListener() {

			@Override
			public void onTouchingLetterChanged(String s) {
				// 该字母首次出现的位置
				int position = adapter.getPositionForSection(s.charAt(0));
				if (position != -1) {
					sortListView.setSelection(position);
				}
			}
		});

		// 更新了数据
		initData();
		// 根据a-z进行排序源数据
		Collections.sort(SourceDateList, pinyinComparator);
		adapter = new ChoiceCrewAdapter(this, SourceDateList);
		sortListView = (ListView) findViewById(R.id.country_lvcountry);
		sortListView.setAdapter(adapter);
		// 初始化listView的侦听
		initsortListViewClistener();

		initCheckAll();

		mClearEditText = (ClearEditText) findViewById(R.id.filter_edit);

		// 根据输入框输入值的改变来过滤搜索
		mClearEditText.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				// 当输入框里面的值为空，更新为原来的列表，否则为过滤数据列表
				filterData(s.toString());
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
			}

			@Override
			public void afterTextChanged(Editable s) {
			}
		});
		this.findViewById(R.id.return_btn).setOnClickListener(
				new View.OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						ChoiceCrewActivity.this.finish();
					}
				});
	}

	protected void initsortListViewClistener() {
		// TODO Auto-generated method stub
		sortListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// 这里要利用adapter.getItem(position)来获取当前position所对应的对象
				// Toast.makeText(getApplication(),
				// ((SortModel) adapter.getItem(position)).getNickName(),
				// Toast.LENGTH_SHORT).show();
				// 这里是记录选中
				// 接着是对checkbox的
				CheckBox check = (CheckBox) view
						.findViewById(R.id.ChoiceCrew_select);
				// check是选中的，那么去掉key，没有选中则添加key到map
				if (check.isChecked()) {
					// if(checkall.isChecked()==true)
					// {
					// checkall.setChecked(false);
					// }
					// 因为在这里checkall设置setChecked为false的时候
					if (checkall.isChecked() == true) {
						isSelectClick = true;
						checkall.setChecked(false);
					}
					check.setChecked(false);
					if (adapter.getMap().containsKey(position)) {
						adapter.getMap().remove(position);
					}

				} else if (check.isChecked() == false) {
					check.setChecked(true);
					adapter.getMap().put(position, adapter.getItem(position));
				}
				Iterator it = adapter.getMap().entrySet().iterator();
				while (it.hasNext()) {
					Map.Entry entry = (Map.Entry) it.next();
					int key = (Integer) entry.getKey();
					String value = ((SortModel) entry.getValue()).getNickName();
//					   
				}

				setButtonUpNumber();
			}
		});

	}

	private void initInterNet() {
		// TODO Auto-generated method stub
		Utils.showPrgress(ChoiceCrewActivity.this);
		MyThreadTool.fixedThreadPool.execute(new Runnable() {
			@Override
			public void run() {
				List = new ArrayList<SortModel>();
				String invite_content = Utils.getRequest(Constants.BadiUrl
						+ "friends?uid="
						+ Utils.getUid(ChoiceCrewActivity.this) + "&page=" + 1
						+ "&pageNum=" + pageNum);
				if (invite_content != null) {
					Results results = Utils.checkResult_NNN(
							ChoiceCrewActivity.this, invite_content);
					if (results != null && !results.getRetmsg().equals("null")) {
						//    
//						   ("我是解析出来的数据:" + results.getRetmsg());
						try {
							List = JSONUtils.getListByJsonString(
									results.getRetmsg(), SortModel.class);
							// mList.addAll(list);
							System.out.println("jiekou"+results.getRetmsg());
							mHandler.sendEmptyMessage(2);
						} catch (Exception e) {
							// TODO Auto-generated catch block
							   
						}
					} else {
						mHandler.sendEmptyMessage(3);
					}
				} else {

					mHandler.sendEmptyMessage(1);
				}

			}
		});
	}

	protected void Updata() {
//		   ("执行更新数据");
		SourceDateList.addAll(filledData(List));
		Collections.sort(SourceDateList, pinyinComparator);
		adapter.notifyDataSetChanged();
	}

	private void initCheckAll() {
		// TODO Auto-generated method stub
		checkall = (CheckBox) this.findViewById(R.id.checkall);
		checkall.setOnCheckedChangeListener(new OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(CompoundButton buttonView,
					boolean isChecked) {
				// TODO Auto-generated method stub
//				   
				if (isChecked == true) {
					if (isSelectClick == true) {
						isSelectClick = false;
					} else {
						adapter.CheckAll();
					}

				} else if (isChecked == false) {
					if (isSelectClick == true) {
						isSelectClick = false;
					} else {
						adapter.ClearAll();
					}

				}
				setButtonUpNumber();
			}
		});
	}

	protected void initData() {
		// TODO Auto-generated method stub
		// SourceDateList =
		// filledData(getResources().getStringArray(R.array.data));
		SourceDateList.addAll(filledData(List));
	}

	/**
	 * 为ListView填充数据
	 * 
	 * @param date
	 * @return
	 */
	private List<SortModel> filledData(List<SortModel> date) {
		List<SortModel> mSortList = new ArrayList<SortModel>();
		if (date != null && !date.isEmpty()) {
//			   ("不为空");
			for (int i = 0; i < date.size(); i++) {
				SortModel sortModel = new SortModel();
				sortModel.setNickName(date.get(i).getNickName());
				sortModel.setHead(date.get(i).getHead());
				sortModel.setId(date.get(i).getId());
				sortModel.setMotto(date.get(i).getMotto());
				sortModel.setIs_firend(date.get(i).getIs_firend());
				// 汉字转换成拼音
				String pinyin = characterParser.getSelling(date.get(i)
						.getNickName());
				String sortString = pinyin.substring(0, 1).toUpperCase();

				// 正则表达式，判断首字母是否是英文字母
				if (sortString.matches("[A-Z]")) {
					sortModel.setSortLetters(sortString.toUpperCase());
				} else {
					sortModel.setSortLetters("#");
				}

				sortModel.setMotto("这只是一项测试");

				mSortList.add(sortModel);
			}
		} else {
//			   ("为空");
		}
		return mSortList;

	}

	/**
	 * 根据输入框中的值来过滤数据并更新ListView
	 * 
	 * @param filterStr
	 */
	private void filterData(String filterStr) {
		List<SortModel> filterDateList = new ArrayList<SortModel>();
		// 是否为空
		if (TextUtils.isEmpty(filterStr)) {
			filterDateList = SourceDateList;
		} else {
			filterDateList.clear();
			for (SortModel sortModel : SourceDateList) {
				String name = sortModel.getNickName();
				if (name.indexOf(filterStr.toString()) != -1
						|| characterParser.getSelling(name).startsWith(
								filterStr.toString())) {
					filterDateList.add(sortModel);
				}
			}
		}

		// 根据a-z进行排序
		Collections.sort(filterDateList, pinyinComparator);
		adapter.updateListView(filterDateList);
	}

	/**
	 * 设置按钮上面的显示的图片的数量
	 */
	protected void setButtonUpNumber() {
		if (adapter != null) {
			int KeyNum = 0;
			Iterator it = adapter.getMap().entrySet().iterator();
			while (it.hasNext()) {
				Map.Entry entry = (Map.Entry) it.next();
				// int key=(Integer) entry.getKey();
				// String value=((SortModel)entry.getValue()).getName();
				//    
				KeyNum++;
			}
			String text = String.format(
					getResources().getString(R.string.Finish_), KeyNum);
			((TextView) (this.findViewById(R.id.Finish_btn))).setText(text);
			Finish_btn.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View arg0) {
					Iterator it = adapter.getMap().entrySet().iterator();
					String id_num = "";
					while (it.hasNext()) {
						Map.Entry entry = (Map.Entry) it.next();
						String value = ((SortModel) entry.getValue()).getId();
						id_num += ((SortModel) entry.getValue()).getId() + ",";
					}
					//    ("打印出来的数据是:"
					// + id_num.substring(0, id_num.length() - 1));
					if (!StringUtil.isNullOrEmpty(id_num)) {
						message = new Message();
						bundle = new Bundle();
						message.what = 4;
//						   
						bundle.putString("res",
								id_num.substring(0, id_num.length() - 1));
                        System.out.println(message);
						message.setData(bundle);
						System.out.println(bundle);
						mHandler.sendMessage(message);
					}
				}
			});
		}
	}

	public ListView getSortListView() {
		return sortListView;
	}

	public void setSortListView(ListView sortListView) {
		this.sortListView = sortListView;
	}

	public ChoiceCrewAdapter getAdapter() {
		return adapter;
	}

	public void setAdapter(ChoiceCrewAdapter adapter) {
		this.adapter = adapter;
	}

	
}
